import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'index.dart';
import 'dart:io';
import 'package:flutter/services.dart';
class SmartService extends StatefulWidget {
  final String url;
  SmartService(this.url);
  @override
  _SmartServiceState createState() => _SmartServiceState();
}

class _SmartServiceState extends State<SmartService> {
  WebViewController _webViewController;

  GlobalKey<_SmartServiceState> _globalKey=GlobalKey<_SmartServiceState>();
  GlobalKey _uniqueKey=GlobalKey(debugLabel: "smartService");
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _globalKey,
      appBar: AppBar(title: Text("智能客服"),centerTitle: true,leading: FlatButton(onPressed: (){
        //Navigator.popAndPushNamed(context, "/index");
        try {
          if (Platform.isAndroid) SystemChannels.textInput.invokeMethod(
              'TextInput.hide');

          Navigator.pop(context);
        }catch(e){
          print(e);
        }
      }, child: Icon(Icons.chevron_left,color: Colors.white,)),),
      body: SafeArea(
        child: WebView(
          key:_uniqueKey,
          initialUrl: widget.url,
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController webViewController) {
            _webViewController=webViewController;
            _webViewController.reload();
          },
          javascriptChannels: <JavascriptChannel>[
            _audioChannel(context),
            _appJavascriptChannel(context),
          ].toSet(),
          navigationDelegate: (NavigationRequest request)  {
            return NavigationDecision.navigate;
          },
          onPageFinished: (String url) {
            print('Page finished loading: $url');
          },
        ),
      ),
    );
  }
  JavascriptChannel _audioChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'Recorder',
        onMessageReceived: (JavascriptMessage message) {


        });
  }
  JavascriptChannel _appJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'App',
        onMessageReceived: (JavascriptMessage message) {
          List<String> mess=message.message.split(":");
          switch(mess[0]){
            case "playAudio":
              String uri;
             for(int i=0;i<mess.length;i++){
              if(i>0){
                if(uri==null){
                  uri=mess[i];
                }else{
                  uri=uri+":"+mess[i];
                }
              }
            }

              break;
            case "stopAudio":

              break;
            case "isPlayingAudio":

            break;
            default:
          }
        });
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    print("smart_service disposed!");
  }
}
